package com.sf.fy.uav.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sf.fy.uav.common.enums.FeedbackStatusEnum;
import com.sf.fy.uav.common.request.order.AnswerFeedbackRequest;
import com.sf.fy.uav.common.request.order.CloseFeedbackRequest;
import com.sf.fy.uav.common.request.order.FeedbackRequest;
import com.sf.fy.uav.common.request.order.SysFeedbackRequest;
import com.sf.fy.uav.common.response.order.SysFeedbackResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.order.controller.FeedbackStatusLogRest;
import com.sf.fy.uav.order.entity.Feedback;
import com.sf.fy.uav.order.entity.FeedbackStatusLog;
import com.sf.fy.uav.order.entity.FeedbackType;
import com.sf.fy.uav.order.entity.OrderInfo;
import com.sf.fy.uav.order.mapper.FeedbackMapper;
import com.sf.fy.uav.order.mapper.FeedbackTypeMapper;
import com.sf.fy.uav.order.mapper.OrderInfoMapper;
import com.sf.fy.uav.order.service.IFeedbackService;
import com.sf.fy.uav.order.service.IOrderInfoService;
import com.sf.fy.uav.user.entity.UserCompany;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 反馈 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2023-06-09
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements IFeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private FeedbackTypeMapper feedbackTypeMapper;

    @Autowired
    private FeedbackStatusLogRest feedbackStatusLogRest;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private IOrderInfoService iOrderInfoService;

    @Autowired
    private IFeedbackService iFeedbackService;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    private final static Integer NUM_CONST = 11;

    @Override
    public Feedback add(FeedbackRequest feedbackRequest) {
        Feedback feedback = BeanUtil.copyProperties(feedbackRequest, Feedback.class);
        feedback.setStatus(FeedbackStatusEnum.SUBMITTED.getStatus());

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String dateString = sdf.format(new Date());
        String workOrderNum = "FYSH" + dateString + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
        feedback.setWorkOrderNum(workOrderNum);
        iFeedbackService.insert(feedback);
        return feedback;
    }

    @Override
    public Long getTotal(@RequestParam(required = false) String orderId,
                         @RequestParam(required = false) String workOrderNum, @RequestParam(required = false) Integer status, @RequestParam(required = false) String feedbackTypeName,
                         @RequestParam(required = false) Integer platformCode) {
        QueryWrapper<Feedback> feedbackQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(feedbackTypeName)) {
            QueryWrapper<FeedbackType> feedbackTypeQueryWrapper = new QueryWrapper<>();
            feedbackTypeQueryWrapper.eq("name", feedbackTypeName);
            FeedbackType feedbackType = feedbackTypeMapper.selectOne(feedbackTypeQueryWrapper);
            if (ObjectUtils.isEmpty(feedbackType)) {
                return 0L;
            }
            feedbackQueryWrapper.eq("feedback_type_id", feedbackType.getId());
        }
        if (!ObjectUtils.isEmpty(platformCode)) {
            feedbackQueryWrapper.eq("platform_code", platformCode);
        }
        if (!ObjectUtils.isEmpty(workOrderNum)) {
            feedbackQueryWrapper.like("work_order_num", workOrderNum);
        }
        if (!ObjectUtils.isEmpty(status)) {
            feedbackQueryWrapper.eq("status", status);
        }
        feedbackQueryWrapper.isNotNull("platform_code");
        if (!ObjectUtils.isEmpty(orderId)) {
            feedbackQueryWrapper.like("order_id", orderId);
        }
        Long cnt = feedbackMapper.selectCount(feedbackQueryWrapper);
        return cnt;
    }


    @Override
    public List<SysFeedbackResponse> getFeedbacks(SysFeedbackRequest sysFeedbackRequest) {
        QueryWrapper<Feedback> feedbackQueryWrapper = new QueryWrapper<>();
        String feedbackTypeName = sysFeedbackRequest.getFeedbackTypeName();
        Integer platformCode = sysFeedbackRequest.getPlatformCode();
        String workOrderNum = sysFeedbackRequest.getWorkOrderNum();
        Integer status = sysFeedbackRequest.getStatus();
        String orderId = sysFeedbackRequest.getOrderId();

        if (!ObjectUtils.isEmpty(feedbackTypeName)) {
            QueryWrapper<FeedbackType> feedbackTypeQueryWrapper = new QueryWrapper<>();
            feedbackTypeQueryWrapper.eq("name", feedbackTypeName);
            FeedbackType feedbackType = feedbackTypeMapper.selectOne(feedbackTypeQueryWrapper);
            if (ObjectUtils.isEmpty(feedbackType)) {
                return new ArrayList<>();
            }
            feedbackQueryWrapper.eq("feedback_type_id", feedbackType.getId());
        }
        if (!ObjectUtils.isEmpty(platformCode)) {
            feedbackQueryWrapper.eq("platform_code", platformCode);
        }
        if (!ObjectUtils.isEmpty(workOrderNum)) {
            feedbackQueryWrapper.like("work_order_num", workOrderNum);
        }
        if (!ObjectUtils.isEmpty(status)) {
            feedbackQueryWrapper.eq("status", status);
        }
        if (!ObjectUtils.isEmpty(orderId)) {
            QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
            orderInfoQueryWrapper.isNotNull("platform_code");
            orderInfoQueryWrapper.like("tc_waybill_no", orderId);
            List<OrderInfo> orderInfos = iOrderInfoService.selectList(orderInfoQueryWrapper);
            if (CollectionUtils.isEmpty(orderInfos)) {
                return new ArrayList<>();
            }
            feedbackQueryWrapper.in("order_id", orderInfos.stream().map(OrderInfo::getId).collect(Collectors.toList()));
        }
        feedbackQueryWrapper.isNotNull("platform_code");
        feedbackQueryWrapper.orderByDesc("create_time");
        Page<Feedback> feedbackPage = new Page<>(sysFeedbackRequest.getPage(), sysFeedbackRequest.getSize());
        IPage<Feedback> feedBackPage = iFeedbackService.selectPage(feedbackPage, feedbackQueryWrapper);
        List<Feedback> feedbacks = feedBackPage.getRecords();
        List<String> feedbackTypeIds = new ArrayList<>();
        List<String> orderIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(feedbacks)) {
            feedbackTypeIds = feedbacks.stream().map(Feedback::getFeedbackTypeId).filter(StringUtils::isNotBlank).toList();
            orderIds = feedbacks.stream().map(Feedback::getOrderId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        }
        List<FeedbackType> feedbackTypes = new ArrayList<>();
        List<OrderInfo> orderInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(feedbackTypeIds)) {
            QueryWrapper<FeedbackType> feedbackTypeQueryWrapper = new QueryWrapper<>();
            feedbackTypes = feedbackTypeMapper.selectList(feedbackTypeQueryWrapper);
            QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
            if (!CollectionUtils.isEmpty(orderIds)) {
                orderInfoQueryWrapper.isNotNull("platform_code");
                orderInfoQueryWrapper.in("id", orderIds);
                orderInfoList = iOrderInfoService.selectList(orderInfoQueryWrapper);
            }
        }

        List<SysFeedbackResponse> sysFeedbackResponses = new ArrayList<>();
        List<FeedbackType> finalFeedbackTypes = feedbackTypes;
        List<OrderInfo> finalOrderInfoList = orderInfoList;
        feedbacks.forEach(feedback -> {
            SysFeedbackResponse sysFeedbackResponse = BeanUtil.copyProperties(feedback, SysFeedbackResponse.class);
            String phoneNumber = sysFeedbackResponse.getPhoneNumber();
            if (!ObjectUtils.isEmpty(phoneNumber) && phoneNumber.length() == NUM_CONST) {
                phoneNumber = phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
                sysFeedbackResponse.setPhoneNumber(phoneNumber);
            }
            if (!CollectionUtils.isEmpty(finalFeedbackTypes)) {
                finalFeedbackTypes.forEach(feedbackType -> {
                    if (StringUtils.isNotBlank(feedbackType.getId()) && feedbackType.getId().equals(feedback.getFeedbackTypeId())) {
                        sysFeedbackResponse.setFeedbackTypeName(feedbackType.getName());
                    }
                });
            }
            if (!CollectionUtils.isEmpty(finalOrderInfoList)) {
                finalOrderInfoList.forEach(orderInfo -> {
                    if (StringUtils.isNotBlank(orderInfo.getId()) && orderInfo.getId().equals(feedback.getOrderId())) {
                        sysFeedbackResponse.setOrderId(orderInfo.getTcWaybillNo());
                    }
                });
            }
            sysFeedbackResponses.add(sysFeedbackResponse);
        });
        return sysFeedbackResponses;
    }

    @Override
    public void close(CloseFeedbackRequest closeFeedbackRequest) {
        Feedback feedback = feedbackMapper.selectById(closeFeedbackRequest.getId());
        if (ObjectUtils.isEmpty(feedback)) {
            throw new RuntimeException("反馈不存在");
        }
        feedback.setProcessedBy(closeFeedbackRequest.getProcessedBy());
        feedback.setStatus(FeedbackStatusEnum.END.getStatus());
        feedback.setUpdateTime(new Date());
        feedbackMapper.updateById(feedback);
        FeedbackStatusLog feedbackStatusLog = new FeedbackStatusLog();
        feedbackStatusLog.setFeedbackId(feedback.getId());
        feedbackStatusLog.setUserId(feedback.getUserId());
        feedbackStatusLog.setContent(closeFeedbackRequest.getReply());
        feedbackStatusLog.setStatus(FeedbackStatusEnum.END.getStatus());
        feedbackStatusLogRest.add(feedbackStatusLog);
    }

    @Override
    public int insert(Feedback entity) {
        String phoneNumber = entity.getPhoneNumber();
        if (!ObjectUtils.isEmpty(phoneNumber)) {
            String encryptPhoneNum = phoneEncoderUtil.encryptString(phoneNumber);
            entity.setPhoneNumber(encryptPhoneNum);
        }
        return feedbackMapper.insert(entity);
    }

    @Override
    public List<Feedback> selectList(Wrapper<Feedback> queryWrapper) {
        List<Feedback> feedbacks = feedbackMapper.selectList(queryWrapper);
        feedbacks.forEach(feedback -> {
            String phoneNumber = feedback.getPhoneNumber();
            if (!ObjectUtils.isEmpty(phoneNumber)) {
                phoneNumber = phoneEncoderUtil.decryptString(phoneNumber);
                feedback.setPhoneNumber(phoneNumber);
            }
        });
        return feedbacks;
    }

    @Override
    public IPage<Feedback> selectPage(Page<Feedback> page, Wrapper<Feedback> queryWrapper) {
        IPage<Feedback> feedbackIPage = feedbackMapper.selectPage(page, queryWrapper);
        List<Feedback> feedbacks = feedbackIPage.getRecords();
        feedbacks.forEach(feedback -> {
            String phoneNumber = feedback.getPhoneNumber();
            if (!ObjectUtils.isEmpty(phoneNumber)) {
                phoneNumber = phoneEncoderUtil.decryptString(phoneNumber);
                feedback.setPhoneNumber(phoneNumber);
            }
        });
        return feedbackIPage;
    }

    @Override
    public Page<Feedback> selectPageListByUserId(Integer page,Integer size,String userId) {
        QueryWrapper<Feedback> feedbackQueryWrapper = new QueryWrapper<>();
        feedbackQueryWrapper.eq("user_id", userId);
        feedbackQueryWrapper.orderByDesc("create_time");
        Page<Feedback> wapperPage = new Page<>(page,size);
        return feedbackMapper.selectPage(wapperPage, feedbackQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void answer(AnswerFeedbackRequest answerFeedbackRequest) {
        Feedback feedback = feedbackMapper.selectById(answerFeedbackRequest.getId());
        if (ObjectUtils.isEmpty(feedback)) {
            throw new RuntimeException("反馈不存在");
        }
        feedback.setProcessedBy(answerFeedbackRequest.getProcessedBy());
        feedback.setStatus(FeedbackStatusEnum.REPLIED.getStatus());
        feedback.setUpdateTime(new Date());
        feedback.setReply(answerFeedbackRequest.getReply());
        feedbackMapper.updateById(feedback);
        FeedbackStatusLog feedbackStatusLog = new FeedbackStatusLog();
        feedbackStatusLog.setFeedbackId(feedback.getId());
        feedbackStatusLog.setContent(answerFeedbackRequest.getReply());
        feedbackStatusLog.setUserId(feedback.getUserId());
        feedbackStatusLog.setStatus(FeedbackStatusEnum.REPLIED.getStatus());
        feedbackStatusLogRest.add(feedbackStatusLog);
    }
}
